<script setup>
import { ElMessage } from "element-plus"
import { computed, reactive, ref } from "vue"
import draggable from "vuedraggable"

// 星期定义（含简体中文对应）
const weekDays = ["周一", "周二", "周三", "周四", "周五", "周六", "周日"]
const timeSlots = [
  "08:00-09:00",
  "09:15-10:15",
  "10:30-11:30",
  "13:00-14:00",
  "14:15-15:15",
  "15:30-16:30"
]

// 示例初始数据
const initialData = {
  timetable: {
    周一: Array.from({ length: 6 }).fill(null),
    // ...其他天的初始化数据
    周日: Array.from({ length: 6 }).fill(null)
  },
  availableCourses: [
    { id: 1, name: "高等数学", teacher: "王教授" },
    { id: 2, name: "大学英语", teacher: "李老师" }
  ]
}

// 响应式数据
const timetable = reactive({ ...initialData.timetable })
const availableCourses = ref([...initialData.availableCourses])
const activeTab = ref("manual")
const newCourse = reactive({ name: "", teacher: "" })

// 表格数据生成
const gridData = computed(() => {
  return timeSlots.map((time, index) => {
    const row = { time, timeSlot: index }
    weekDays.forEach((day) => {
      row[day.toLowerCase()] = getCourse(day, index)
    })
    return row
  })
})

// 课时数据存取方法
function getCourse(day, timeSlot) {
  return timetable[day]?.[timeSlot] || null
}

function updateCourse(day, timeSlot, course) {
  if (!timetable[day]) timetable[day] = Array.from({ length: 6 }).fill(null)
  timetable[day][timeSlot] = course
}

// 新课程表单处理
function addNewCourse() {
  if (!newCourse.name || !newCourse.teacher) {
    ElMessage.warning("请填写完整的课程信息")
    return
  }

  availableCourses.value.push({
    id: Date.now(),
    ...newCourse,
    conflict: false
  })

  newCourse.name = ""
  newCourse.teacher = ""
  ElMessage.success("课程添加成功！")
}

// 课时变更处理
function handleCourseUpdate({ day, timeSlot, course }) {
  const prevCourse = getCourse(day, timeSlot)

  // 原课程放回可用列表
  if (prevCourse) {
    availableCourses.value.push(prevCourse)
  }

  // 放置新课程
  if (course) {
    updateCourse(day, timeSlot, course)
    availableCourses.value = availableCourses.value.filter(c => c.id !== course.id)
  }

  detectConflicts()
}

// 冲突检测（核心逻辑）
function detectConflicts() {
  const teacherMap = new Map()

  // 第一次循环：统计数据
  weekDays.forEach((day) => {
    timetable[day]?.forEach((course, timeSlot) => {
      if (!course) return
      const key = `${course.teacher}-${timeSlot}`
      teacherMap.set(key, (teacherMap.get(key) || 0) + 1)
    })
  })

  // 第二次循环：标记冲突
  weekDays.forEach((day) => {
    timetable[day] = timetable[day].map((course) => {
      if (!course) return null
      const key = `${course.teacher}-${course.timeSlot}`
      return {
        ...course,
        conflict: teacherMap.get(key) > 1
      }
    })
  })
}
</script>

<template>
  <div class="timetable-container">
    <!-- 顶部导航 -->
    <el-menu mode="horizontal" :default-active="activeTab" @select="handleTabChange">
      <el-menu-item index="manual">
        手工排课
      </el-menu-item>
      <el-menu-item index="auto">
        自动排课(预留)
      </el-menu-item>
    </el-menu>

    <div class="timetable-content">
      <!-- 左侧可排课程区 -->
      <div class="course-pool">
        <h3>可排课程 ({{ availableCourses.length }})</h3>

        <!-- 新加课程表单 -->
        <el-form @submit.prevent="addNewCourse" class="course-form">
          <el-input v-model="newCourse.name" placeholder="课程名称" required />
          <el-input v-model="newCourse.teacher" placeholder授课教师" required class="mt-10" />
          <el-button native-type="submit" type="primary" class="mt-10 w-full">
            添加新课程
          </el-button>
        </el-form>

        <!-- 可拖拽课程列表 -->
        <draggable
          v-model="availableCourses"
          group="timetable"
          item-key="id"
          :component-data="{ class: 'course-list' }"
        >
          <template #item="{ element }">
            <div class="course-item" :class="{ 'has-conflict': element.conflict }">
              <div class="course-name">
                {{ element.name }}
              </div>
              <div class="course-teacher">
                {{ element.teacher }}
              </div>
            </div>
          </template>
        </draggable>
      </div>

      <!-- 右侧课程表主体 -->
      <div class="timetable-main">
        <el-table :data="gridData" border style="width: 100%" row-class-name="table-row">
          <!-- 时间轴 -->
          <el-table-column prop="time" label="时间" width="120" fixed />

          <!-- 星期列（动态生成） -->
          <el-table-column
            v-for="(day, idx) in weekDays"
            :key="idx"
            :label="day"
            :prop="day.toLowerCase()"
          >
            <template #default="{ row }">
              <timetable-cell
                :day="day"
                :time-slot="row.timeSlot"
                :course="getCourse(day, row.timeSlot)"
                @update-course="handleCourseUpdate"
              />
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
  </div>
</template>

<style scoped>
.timetable-container {
  padding: 20px;
  background: #f5f7fa;
  min-height: 100vh;
}

.timetable-content {
  display: grid;
  grid-template-columns: 300px 1fr;
  gap: 20px;
  margin-top: 20px;
}

.course-pool {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.course-form {
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid #ebeef5;
}

.course-list {
  min-height: 300px;
  max-height: 60vh;
  overflow-y: auto;
}

.course-item {
  background: #f8f9fa;
  border-radius: 4px;
  padding: 10px;
  margin: 5px 0;
  cursor: move;
  transition: all 0.3s;

  &:hover {
    transform: translateX(5px);
    box-shadow: 2px 2px 6px rgba(0, 0, 0, 0.1);
  }

  &.has-conflict {
    background: #fff3f3;
    border: 1px solid #ff4d4f;
  }
}

.timetable-main {
  background: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

:deep(.table-row) .cell {
  min-height: 80px;
  vertical-align: top;
}
</style>
